package com.itjcloud.iot.gateway.model;

import com.fasterxml.jackson.annotation.JsonAlias;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.oauth2.jwt.Jwt;

import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

/**
 * token中的基本信息
 */

@Data
@NoArgsConstructor
public class CommonTokenInfo {

    /**
     * 租户id
     */
    private Long tenantId;

    /**
     * 组织id
     */
    private Long orgId;

    /**
     * 子组织id
     */
    @JsonAlias("schoolId")
    private Long childOrgId;


    /**
     * 用户id
     */
    private Long userId;


    /**
     * token过期时间
     */
    private Instant exp;
    /**
     * 登录的入口id
     */
    private String clientId;


    /**
     * token签发时间
     */
    private Instant iat;


    /**
     * 匿名token或者jwt中的jti
     */
    private String jti;


    /**
     * 是否认证
     */
    private boolean authenticated;

    private Long deviceId;


    /**
     * 构造函数, 把jwt的数据初始化到项目中
     *
     * @param jwt jwt的数据
     */
    public CommonTokenInfo(Jwt jwt) {
        this.tenantId = jwt.getClaim(CommonTokenHeaderEnum.TENANT_ID.getJwtName());
        this.orgId = jwt.getClaim(CommonTokenHeaderEnum.ORG_ID.getJwtName());
        this.childOrgId = jwt.getClaim(CommonTokenHeaderEnum.CHILD_ORG_ID.getJwtName());
        this.userId = jwt.getClaim(CommonTokenHeaderEnum.USER_ID.getJwtName());
        this.jti = jwt.getClaim(CommonTokenHeaderEnum.JTI.getJwtName());
        this.tenantId = jwt.getClaim(CommonTokenHeaderEnum.TENANT_ID.getJwtName());
        this.clientId = jwt.getClaim(CommonTokenHeaderEnum.CLIENT_ID.getJwtName());
        this.authenticated = true;
    }

    public Map<String, String> toMap() {
        Map<String, String> tokenInfoMap = new HashMap<>();
        tokenInfoMap.put(CommonTokenHeaderEnum.TENANT_ID.getHeaderName(), String.valueOf(tenantId));
        tokenInfoMap.put(CommonTokenHeaderEnum.ORG_ID.getHeaderName(), String.valueOf(orgId));
        tokenInfoMap.put(CommonTokenHeaderEnum.CHILD_ORG_ID.getHeaderName(), String.valueOf(childOrgId));
        tokenInfoMap.put(CommonTokenHeaderEnum.USER_ID.getHeaderName(), String.valueOf(userId));
        tokenInfoMap.put(CommonTokenHeaderEnum.JTI.getHeaderName(), jti);
        tokenInfoMap.put(CommonTokenHeaderEnum.CLIENT_ID.getHeaderName(), clientId);
        tokenInfoMap.put(CommonTokenHeaderEnum.AUTHENTICATED.getHeaderName(), String.valueOf(authenticated));
        tokenInfoMap.put(CommonTokenHeaderEnum.DEVICE_ID.getHeaderName(), String.valueOf(deviceId));
        return tokenInfoMap;
    }

}
